<?php
declare (strict_types=1);

namespace app\index\controller;

use app\model\ArticleModel;
use app\model\CategoryModel;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;

class Article
{
    public function index()
    {
        $params = Request::param();
        $validate = Validate::rule([
            'category_id' => 'between:1,' . PHP_INT_MAX,
        ]);
        if (!$validate->check($params)) {
            echo $validate->getError();
            exit();
        }

        parse_str(Request::query(), $queryParams);

        $articleList = ArticleModel::where('category_id', '=', $params['category_id'])
            ->order('add_time desc')
            ->paginate(['list_rows' => 10, 'query' => $queryParams]);
        return View::fetch('index/index', [
            'articleList' => $articleList,
        ]);
    }

    // 文章详情页
    public function detail()
    {
        $articleId = Request::param("article_id");
        $validate = Validate::rule([
            'article_id|文章id' => 'require|between:1,' . PHP_INT_MAX,
        ]);
        if (!$validate->check(['article_id' => $articleId])) {
            echo $validate->getError();
            exit();
        }

        $article = ArticleModel::find($articleId);
        if (!$article) {
            echo '文章不存在';
            exit();
        }

        return View::fetch('', [
            'article' => $article,
        ]);
    }
}
